define(['jquery', 'bootstrap', 'frontend', 'backend','form', 'template','highcharts'], function ($, undefined, Frontend, Backend, Form, Template,Highcharts) {
    var validatoroptions = {
        invalid: function (form, errors) {
            $.each(errors, function (i, j) {
                Layer.msg(j);
            });
        }
    };
    var Controller = {
        info:function(){
            var apps = Controller.appsdata();
            if(apps == true){
                $('.panel-heading').hide();
                return false;
            }
            $('.panel-heading').show();
            var app_id = $("#app_id").val();
            Controller.snapdata(app_id,0);
            Controller.flowdata(app_id,0);
            Controller.linkdata(app_id,0);
            var i = setInterval(function(){
                Controller.snapdata(app_id,0);
                Controller.flowdata(app_id,0);
                Controller.linkdata(app_id,0);
            }, 60000);
            var $app_tab_ul = $("#app_tab_ul");     
            $app_tab_ul.on("click","a.app-tab",function(){
                var key = $(this).attr('key');
                var app_id_tab = $(this).attr('appid');
                Controller.snapdata(app_id_tab,key);
                Controller.flowdata(app_id_tab,key);
                Controller.linkdata(app_id_tab,key);
                clearInterval(i);
                // console.log(j);
                // clearInterval(j);
                var j = setInterval(function(){
                    Controller.snapdata(app_id_tab,key);
                    Controller.flowdata(app_id_tab,key);
                    Controller.linkdata(app_id_tab,key);
                }, 60000);

            });
        },
        appsdata:function(){
            var sign = null;
            $.ajax({
                type:"GET",
                url: '/index/app/apps',
                async: false,//使用同步的方式,true为异步方式
                dataType:"json",
                success:function(msg){
                    var msg = eval('(' + msg + ')');
                    var folw_str = "关键应用";
                    if(msg.code == 401){
                        Backend.api.toastr.error(msg.msg);
                        window.location.href='/index/user/login';
                        sign = true;
                        return false;
                    }
                    if(msg.code == 0 || msg.code == 403){
                        Backend.api.toastr.error(folw_str+msg.msg);
                        sign = true;
                        return false;
                    }
                }
            });
            return sign;
        },
        snapdata:function(app_id,key){
            $.ajax({
              type:"GET",
              url: '/index/app/flow',
              data:{type:'snap',appid:app_id}, 
              dataType:"json",
              success:function(msg){
                // var random = Math.floor(Math.random()*(10-30+1)+30);
                // $("#flow-up-"+key).html(random);
                // $("#flow-down-"+key).html(random);
                var folw_str = "流量（上行/下行）";
                if(msg.code == 401){
                    $(".flow-display-"+key).hide();
                    Backend.api.toastr.error(msg.msg);
                    window.location.href='/index/user/login';
                    return false;
                }
                if(msg.code == 0 || msg.code == 403){
                    $(".flow-display-"+key).hide();
                    Backend.api.toastr.error(folw_str+msg.msg);
                    return false;
                }
                $(".flow-display-"+key).show();
                var flow = new Array();
                var up = msg.data.flow_up_down.split("/");
                $("#flow-up-"+key).html(up[0]);
                $("#flow-down-"+key).html(up[1]);
              }  
            });
        },
        flowdata:function(app_id,key){
            $.ajax({
              type:"GET",
              url: '/index/app/flow',
              data:{type:'flow',appid:app_id}, 
              dataType:"json",
              success:function(msg){
                    Controller.chartdraw('bps', 'flow-hour-'+key, msg.data,'24小时流量趋势',msg.code,msg.msg);
                }
            });
        },
        linkdata:function(app_id,key){
            $.ajax({
              type:"GET",
              url: '/index/app/flow',
              data:{type:'link',appid:app_id}, 
              dataType:"json",
              success:function(msg){
                    Controller.chartdraw('flow', 'connect-hour-'+key, msg.data,'24小时连接趋势',msg.code,msg.msg);
                }
            });
        },
        numberformat:function(num){
            if (num >= 1024 * 1024 * 1024)
                return ((num / (1024 * 1024 * 1024))).toFixed(2) + 'G';
            else
            if (num >= 1024 * 1024)
                    return ((num / (1024 * 1024))).toFixed(2) + 'M';
            else     
            if (num >= 1024)
                    return ((num / 1024)).toFixed(2) + 'K';
            else
                    return num;
        },
        chartdraw:function(tag,render,json,text_str,code,msg){
            if(code == 401){
                Backend.api.toastr.error(msg);
                window.location.href='/index/user/login';
                return false;
            }
            if(code == 0 || code == 403){
                Backend.api.toastr.error(text_str+msg);
                return false;
            }
            Highcharts.setOptions({ global: { useUTC: false } });
            if (tag == "bps")
                units = "bits/s";
            else 
                units = "#flowcont";
            var options = {
                chart:{
                    renderTo:render,
                    borderRadius:0,
                    defaultSeriesType:'area',
                    borderWidth: 1,
                    // borderColor:'#D3DCEB', //边框颜色设置
                    borderColor:false,
                    borderRadius:4
                },title:{
                    text:text_str,
                    style: {
                        // color: 'red',   //字体颜色
                        fontSize:"14px", //字体大小
                        "font-weight": "bold",
                    }
                },xAxis:{
                    type:'datetime',
                    tickPixelInterval:80,
                    labels:{
                        rotation:-45,
                        align:'right',
                        style:{font:'normal 10px sans-serif', color:'#000000'}
                    }
                },yAxis:{
                    min:0,
                    tickPixelInterval:30,
                    labels:{
                        style:{font:'normal 10px sans-serif', color:'#000000'}
                    },
                    title:{ text:units },
                    plotLines:[{value:0,width:0.5}]
                },
                exporting: {
                    enabled: false
                },//隐藏导出
                credits: { 
                    enabled: false
                },//隐藏右下角highcharts的链接
                // legend:{enabled:true, align:'right', symbolHeight:8, symbolWidth:8, symbolRadius:8, verticalAlign:'top', y:0, margin: 15, 
                //     padding: 0, lineHeight:1,itemStyle:{fontSize:'10', fontWeight:'thin', color:'#aaa'}
                // },plotOptions:{area:{stacking:'false',lineWidth:0,marker:{enabled:false}}, spline: {lineWidth:0.5}
                // },credits:{enabled:false},
                tooltip:{
                    shared: true,
                    formatter: function () {
                        var s1 = '<span style="font:normal 10px sans-serif;">' + Highcharts.dateFormat("%m/%d %H:%M", this.x)+'</span>';
                        var s2 = '', s3='';
                        var cnt = 0;
                        $.each(this.points, function () {
                            cnt += this.y;
                            s2 += '<br/><span style="font:normal 10px sans-serif;color:#666;padding:1px 0;">'+this.series.name+': '+
                                Controller.numberformat(this.y)+'</span>';
                        });
                        s3 = '<br><span style="margin-top:3px; font-size:11px;">合计:'+Controller.numberformat(cnt)+'</span>';
                        return s1+s2+s3;
                    }
                },series:[]
            }
            if (tag == "bps") {
                options.series = [{name: '下行速率', data:[]}, {name: '上行速率', data:[], type: 'spline'}]
                options.series[0].data = json.bpsin;
                options.series[1].data = json.bpsout;
            }else{
                options.series = [{name: '连接数', data:[], type: 'spline'}]
                options.series[0].data = json.flow;
            }
            new Highcharts.Chart(options);
        },
        login: function () {
            //本地验证未通过时提示
            $("#login-form").data("validator-options", validatoroptions);

            $(document).on("change", "input[name=type]", function () {
                var type = $(this).val();
                $("div.form-group[data-type]").addClass("hide");
                $("div.form-group[data-type='" + type + "']").removeClass("hide");
                $('#resetpwd-form').validator("setField", {
                    captcha: "required;length(4);integer[+];remote(" + $(this).data("check-url") + ", event=resetpwd, " + type + ":#" + type + ")",
                });
                $(".btn-captcha").data("url", $(this).data("send-url")).data("type", type);
            });

            //为表单绑定事件
            Form.api.bindevent($("#login-form"), function (data, ret) {
                setTimeout(function () {
                    location.href = ret.url ? ret.url : "/";
                }, 1000);
            });

            Form.api.bindevent($("#resetpwd-form"), function (data) {
                Layer.closeAll();
            });

            $(document).on("click", ".btn-forgot", function () {
                var id = "resetpwdtpl";
                var content = Template(id, {});
                Layer.open({
                    type: 1,
                    title: __('Reset password'),
                    area: ["450px", "355px"],
                    content: content,
                    success: function (layero) {
                        Form.api.bindevent($("#resetpwd-form", layero), function (data) {
                            Layer.closeAll();
                        });
                    }
                });
            });
        },
        register: function () {
            //本地验证未通过时提示
            $("#register-form").data("validator-options", validatoroptions);

            //为表单绑定事件
            Form.api.bindevent($("#register-form"), function (data, ret) {
                setTimeout(function () {
                    location.href = ret.url ? ret.url : "/";
                }, 1000);
            });
        },
        changepwd: function () {
            //本地验证未通过时提示
            $("#changepwd-form").data("validator-options", validatoroptions);

            //为表单绑定事件
            Form.api.bindevent($("#changepwd-form"), function (data, ret) {
                setTimeout(function () {
                    location.href = ret.url ? ret.url : "/";
                }, 1000);
            });
        },
        profile: function () {
            // 给上传按钮添加上传成功事件
            $("#plupload-avatar").data("upload-success", function (data) {
                var url = Fast.api.cdnurl(data.url);
                $(".profile-user-img").prop("src", url);
                Toastr.success(__('Upload successful'));
            });
            Form.api.bindevent($("#profile-form"));
            $(document).on("click", ".btn-change", function () {
                var that = this;
                var id = $(this).data("type") + "tpl";
                var content = Template(id, {});
                Layer.open({
                    type: 1,
                    title: "修改",
                    area: ["400px", "250px"],
                    content: content,
                    success: function (layero) {
                        var form = $("form", layero);
                        Form.api.bindevent(form, function (data) {
                            location.reload();
                            Layer.closeAll();
                        });
                    }
                });
            });
        }
    };
    return Controller;
});